#include "../../Helix.h"
#include "../../HObject.h"
#include "Image.h"
#include "ImageFactory.h"
#include "BMPImage.h"
#include "TGAImage.h"
#include "PNGImage.h"
#include "../../Log.h"
#include "../../Util/StringUtil.h"
#include <string>

using namespace std;

namespace helix
{
	ImageFactory::ImageFactory() : HObject()
	{

	}

	ImageFactory::~ImageFactory()
	{

	}

	Image* ImageFactory::loadImage(const char* fileName)
	{
		logFile.Println("ImageFactory:: Loading image from %s...",fileName);

		string fName = fileName;
		size_t extPos = fName.find_last_of('.');
		if(extPos == fName.size() || extPos == fName.size()-1)
		{
			logFile.Error("ImageFactory:: Could not load image without an extension.");
			return NULL;
		}

		string ext = fName.substr(extPos+1);

		Image *ret = NULL;	//Image to return 
		if(StringUtil::compareIgnoreCase(&ext,&string("bmp")) == 0)			//Is this a BMP
		{
			ret = new BMPImage(fileName);
		}
		else if(StringUtil::compareIgnoreCase(&ext,&string("tga")) == 0)	//Is this a TGA
		{
			ret = new TGAImage(fileName);
		}
		else if(StringUtil::compareIgnoreCase(&ext,&string("png")) == 0)	//Is this a PNG
		{
			ret = new PNGImage(fileName);
		}
		else																//Extension not supported
		{
			logFile.Error("ImageFactory:: Could not load image. Extension \"%s\" not supported.",ext.c_str());
			return NULL;
		}

		if(ret!=NULL && ret->isLoaded())		//Make sure the image loaded correctly
		{
			logFile.Println("ImageFactory:: Successfully loaded image: %s",fileName);
		}
		else			//If not, print an error and clean up
		{
			logFile.Error("ImageFactory:: An error occured while trying to load image: %s",fileName);
			if(ret!=NULL)
				delete ret;
			return NULL;
		}

		return ret;		//Return the image
	}

	void ImageFactory::deleteImage(Image *image)
	{
		if(image == NULL)
			return;

		delete image;
	}
	
}



